import { defineStore, acceptHMRUpdate } from 'pinia'
import { useStorage } from '@vueuse/core'
import defaultSettings from '@/utils/settings'
import { toggleDarkMode } from '@/utils/theme'
import { ThemeEnum } from '@/enums/ThemeEnum'

type SettingsValue = boolean | string

export const useSettingsStore = defineStore('setting', () => {
  // 侧边栏 Logo
  const sidebarLogo = useStorage<boolean>('sidebarLogo', defaultSettings.sidebarLogo)
  // 主题颜色
  const themeColor = useStorage<string>('themeColor', defaultSettings.themeColor)
  // 主题模式
  const theme = useStorage<string>('theme', defaultSettings.theme)
  // 记住密码
  const rememberChecked = useStorage<boolean>('rememberChecked', false)

  // 监听主题变化
  watch(
    theme,
    theme => {
      toggleDarkMode(theme === ThemeEnum.DARK)
    },
    { immediate: true }
  )

  // 设置更改函数
  const settingsMap: Record<string, Ref<SettingsValue>> = {
    sidebarLogo
  }

  function changeSetting({ key, value }: { key: string; value: SettingsValue }) {
    const setting = settingsMap[key]
    if (setting) setting.value = value
  }

  function changeTheme(val: string) {
    theme.value = val
  }

  function changeThemeColor(color: string) {
    themeColor.value = color
  }

  function changeRememberChecked(val: boolean) {
    rememberChecked.value = val
  }

  return {
    sidebarLogo,
    themeColor,
    theme,
    rememberChecked,
    changeSetting,
    changeTheme,
    changeThemeColor,
    changeRememberChecked
  }
})

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useSettingsStore, import.meta.hot))
}
